﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Heimdallr
{
    /// <summary>
    /// Provides a set of extension methods for service element.
    /// </summary>
    public static class ServiceElementExtensions
    {
        /// <summary>
        /// Creates a generic element controller for current service element.
        /// </summary>
        /// <typeparam name="TElement">The type of service element.</typeparam>
        /// <param name="serviceElement">A service element.</param>
        /// <returns>A generic element controller of current service element.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="serviceElement"/> is null.</exception>
        public static ServiceElementController<TElement> CreateController<TElement>(this TElement serviceElement)
            where TElement : ServiceElement
        {
            if (serviceElement == null)
                throw new ArgumentNullException("serviceElement");

            return new ServiceElementController<TElement>(serviceElement);
        }

        /// <summary>
        /// Finds out all trigger elements from a collection of service controllers.
        /// </summary>
        /// <param name="controllers">A collection of service controllers.</param>
        /// <returns>All trigger elements of a collection of service controllers.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="controllers"/> is null.</exception>
        public static IEnumerable<ITriggerElement> GetTriggerElements(this IEnumerable<ServiceElementController> controllers)
        {
            if (controllers == null)
                throw new ArgumentNullException("controllers");

            return from controller in controllers
                   where controller.ElementBase is ITriggerElement
                   select controller.ElementBase as ITriggerElement;
        }

        /// <summary>
        /// Finds out all notify elements from a collection of service controllers.
        /// </summary>
        /// <param name="controllers">A collection of service controllers.</param>
        /// <returns>All notify elements of a collection of service controllers.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="controllers"/> is null.</exception>
        public static IEnumerable<INotifyElement> GetNotifyElements(this IEnumerable<ServiceElementController> controllers)
        {
            if (controllers == null)
                throw new ArgumentNullException("controllers");

            return from controller in controllers
                   where controller.ElementBase is INotifyElement
                   select controller.ElementBase as INotifyElement;
        }
    }
}
